package com.example.java_message_queue.common;

import java.io.*;

// 本身不处理异常. 交给外部处理.
public class BinaryTool {
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            object = objectInputStream.readObject();
        }
        return object;
    }

    public static byte[] toBytes(Object object) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(object);
        }
        return byteArrayOutputStream.toByteArray();
    }
}
